package myJs

import scala.collection.immutable.SeqMap
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.Implicits._
import myJs.Utils.g
import myJs.myPkg.{ColumnOptions, TableOptions}

import scala.scalajs.js
import js.JSConverters._
import myJs.myPkg.jquery._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.JSON


/**
 * Created by yz on 13/11/2020
 */
@JSExportTopLevel("Browse")
object Browse {

  val tableId = "table"
  val map = SeqMap("geneId" -> "Gene ID", "chr" -> "Chr", "start" -> "Start", "end" -> "End", "strand" -> "Ori",
    "nrName" -> "NR_tophit_name", "nrDescription" -> "NR_tophit_description", "nrSimil" -> "NR_topHSP_%-Simil",
    "gos" -> "GOs", "nog" -> "NOG", "function" -> "Function", "ko" -> "KO/Gene_ID",
    "keggGeneName" -> "KEGG_GENE_NAME",
    "subjectId" -> "Subject_id", "subjectDb" -> "Subject_DB", "subjectAnno" -> "Subject_annotation",
    "swiss" -> "Swiss")

  @JSExport("init")
  def init = {
    initTable
    refreshTable
  }

  def refreshTable = {
    val url = g.jsRoutes.controllers.GenomeBrowseController.getAllBgAnnos().url.toString
    Ajax.get(url = s"${url}").map { xhr =>
      $("#charts").html("")
      val data = xhr.responseText.toJArJDJAn.toMyJDS
      $(s"#${tableId}").bootstrapTable("load", data)
    }
  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case "geneId"=>
      val url = g.jsRoutes.controllers.GenomeBrowseController.detailInfoBefore().url.toString
      a(href := s"${url}?geneId=${row("geneId")}", target := "_blank",title:="more", s"${v.toString}")
    case _ => v
  }

  def expStyle(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[Any]) => columnName match {
    case _ => v
  }

  def initTable = {
    $("#charts").html("<img src='/assets/images/loading.gif'/>")
    val columnNames = map.keyList
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      val fmt = tbFmt(columnName)
      val style = expStyle(columnName)
      val basicOptions = ColumnOptions.field(columnName).title(title).titleTooltip(title).sortable(true).
        formatter(fmt).cellStyle(style)
      columnName match {
        case x if List("size", "uploadTime", "fileName", "comment", "tags").contains(x) => basicOptions.
          sortable(false).operateable(true)
        case _ => basicOptions
      }
    }
    val options = TableOptions.columns(columns.toJSArray).searchOnButton(false).filterControl(false)
    $(s"#${tableId}").bootstrapTable(options)
    Tool.refreshCheckboxView(map.tail, "checkbox")
    val hideColumns = map.keyList.drop(6)
    hideColumns.foreach { x =>
      $(s"#${tableId}").bootstrapTable("hideColumn", x)
      $(s"input:checkbox[value='${x}']").attr("checked", false)
    }
  }

}
